
import { Component, director, isValid } from 'cc';
import { Clips, Key, TaskType, aaEvent, atrributes,storageKey } from 'db://assets/scripts/frame/common/Enums';
import utilsMgr from 'db://assets/scripts/frame/common/Utils';
import soundMgr from 'db://assets/scripts/frame/managers/SoundMgr';


class DataMgr extends Component{

    private _tempStorages: { [key: string]: any } = {};

    set(key: storageKey, val: any) {
        const name = key.name;
        utilsMgr.save(name, val);
        this._tempStorages[name] = val;
        return val;
    }
    get(key: storageKey) {
        const name = key.name;
        const type = key.type;
        const res = this._tempStorages[name];
        if (res) {
            return res;
        } else {
            let data = utilsMgr.load(name, type);
            if (!isValid(data)) {
                data = key.default;
            }
            this._tempStorages[name] = data;
            return data;
        }
    }


    updateData(arrs: {}, keys: string[], obj: {}) {
        keys.forEach((key) => {
            if (obj.hasOwnProperty(key)) {
                const value = Number(obj[key]) || 0;
                arrs[key] = value;
            } else {
                arrs[key] = 0;
            }
        })
    }


   
    addHeart(num:number){
        let amount  = this.get(Key.Hearts);
        amount = amount + num/100;
        if(amount<0) amount = 0
        this.set(Key.Hearts,amount);
        director.emit(aaEvent.hearts, amount);
        director.emit(aaEvent.updateTaskAmount, TaskType.HEART,amount);

    }
   
    subCurrency(key:storageKey, num: number) {
        let amount = this.get(key);
        amount = amount - num;
        if (amount < 0) {
            return false;
        }
        this.set(key,amount)
        director.emit(aaEvent.currency, key, amount);
        return true;
    }
    addCurrency(key:storageKey, num: number,delay = 0) {
        soundMgr.play(Clips.gold);

        let amount = this.get(key);
        amount += num;
        this.set(key,amount)
        this.scheduleOnce(()=>{
            director.emit(aaEvent.currency, key, amount);
        },delay)
    }

}
const dataMgr = new DataMgr;

export default dataMgr;